//导入vue-router
import {createRouter,createWebHistory} from 'vue-router'
import Login from "@/views/Login.vue";
import Index from "@/views/Index.vue";
import {userTokenStore} from "@/stores/token.js";
import FictionManage from "@/fiction/FictionManage.vue";
import FictionCategoryManage from "@/fiction/FictionCategoryManage.vue";
import UserInfo from "@/user/UserInfo.vue";
import UserPassword from "@/user/UserPassword.vue";
import WebFictionList from "@/views/webFiction/WebFictionList.vue";
import WebFictionInfo from "@/views/webFiction/WebFictionInfo.vue";
import WebShowFiction from "@/views/webFiction/WebShowFiction.vue";

const routes = [
    //登录
    {path: '/login', name:'Login', component: Login},
    //首页
    {
        path: '/',
        component: Index,
        children:[
            {path:'/fiction/manage', name:'FictionManage', component:FictionManage},
            {path:'/fiction/category', component:FictionCategoryManage},
            {path:'/user/info', component:UserInfo},
            {path:'/user/password', component:UserPassword},
            //搜索小说页面
            {path: '/searchFictionList', component: WebFictionList},
            //小说详情页
            {path: '/webFictionInfo', component: WebFictionInfo},
            {path: '/webShowFiction', component: WebShowFiction}
        ]
    }
]
const router = createRouter({
    routes:routes,
    history:createWebHistory()
})

router.beforeEach(async (to, from) => {
    const userToken = userTokenStore()
    if (
        // 检查用户是否已登录
        !userToken.getToken() &&
        // ❗️ 避免无限重定向
        to.name !== 'Login'
    ) {
        // 将用户重定向到登录页面
        return { name: 'Login' }
    }
})

export default router